package com.suishoupai.xmb.utils;

import com.suishoupai.xmb.Security.MyUserDetail;
import com.suishoupai.xmb.entity.RoleEnum;
import com.suishoupai.xmb.entity.User;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Created by caojian on 2017/3/22.
 */
public class SecurityUserUtil {

    /**
     * 获取当前用户role
     *
     * @return
     */
    public static List<RoleEnum> getRoles() {
        List<RoleEnum> roles = new ArrayList<RoleEnum>();
        Collection<? extends GrantedAuthority> authorities = SecurityContextHolder.getContext().getAuthentication().getAuthorities();
        for (GrantedAuthority grantedAuthority : authorities) {
            if (grantedAuthority.toString().equals(RoleEnum.ADMIN.getValue())) {
                roles.add(RoleEnum.ADMIN);
            } else if (grantedAuthority.toString().equals(RoleEnum.USER.getValue())) {
                roles.add(RoleEnum.USER);
            } else if (grantedAuthority.toString().equals(RoleEnum.SALE.getValue())) {
                roles.add(RoleEnum.SALE);
            } else {
                throw new RuntimeException("不认识的账号role:" + grantedAuthority.toString());
            }
        }
        return roles;
    }

    /**
     * 设置为已认证（微信登录后设置为已认证，说明：微信登录与网页登录是有区别的。）
     *
     * @param user
     */
    public static void setAuth(User user) {
        SecurityContext s = SecurityContextHolder.getContext();
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        authorities.add(new SimpleGrantedAuthority(user.getRole()));
        Authentication auth = new UsernamePasswordAuthenticationToken(new MyUserDetail(user), null, authorities);
        s.setAuthentication(auth);
    }

    /**
     * 验证当前用户是否拥有该role
     *
     * @param verifyRole
     * @return
     */
    public static boolean hasRole(RoleEnum verifyRole) {
        List<RoleEnum> roles = getRoles();
        for (RoleEnum role : roles) {
            if (verifyRole.getValue().equals(role.getValue())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取当前登录user
     *
     * @return
     */
    public static User getUser() {
        MyUserDetail myUserDetail = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return myUserDetail.getUser();
    }
}
